package com.example.jetgege.smssenddemo;

import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by jetgege on 2017/3/1.
 */

public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        //为content://sms的数据改变注册监听器
        getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, new SmsObserver(new Handler()));
    }


    //一个继承自ContentObserver的监听器类
   public class SmsObserver extends ContentObserver {

        public SmsObserver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            //查询发送箱中的短信
            Cursor cursor = getContentResolver().query(Uri.parse(
                    "content://sms/outbox"), null, null, null, null);
            //遍历查询结果获取用户正在发送的短信
            while (cursor.moveToNext()) {
                StringBuffer sb = new StringBuffer();
                //获取短信的发送地址
                sb.append("发送地址：" + cursor.getString(cursor.getColumnIndex("address")));
                //获取短信的标题
                sb.append("\n标题：" + cursor.getString(cursor.getColumnIndex("subject")));
                //获取短信的内容
                sb.append("\n内容：" + cursor.getString(cursor.getColumnIndex("body")));
                //获取短信的发送时间
                Date date = new Date(cursor.getLong(cursor.getColumnIndex("date")));
                //格式化以秒为单位的日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");
                sb.append("\n时间：" + sdf.format(date));
                System.out.println("查询到的正在发送的短信：" + sb.toString());
                Toast.makeText(MyService.this, sb.toString(), Toast.LENGTH_LONG).show();

            }
            super.onChange(selfChange);
        }
    }

        @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}